package com.fzt.system.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzt.system.domain.entity.SysUserRoleEntity;
import com.fzt.system.mapper.SysUserRoleMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色关联服务
 * </p>
 *
 * @author 非洲铜
 * @since 2022-12-13
 */
@Service
@AllArgsConstructor
public class SysUserRoleService extends ServiceImpl<SysUserRoleMapper, SysUserRoleEntity> {

    /**
     * 保存或者修改用户角色的关联关系
     *
     * @param userId     用户ID
     * @param roleIdList 角色ID列表
     */
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {
        List<Long> dbRoleIdList = getRoleIdList(userId);

        // 最终以传入的roleIdList为准
        // 传入的有，数据库没有，新增
        Collection<Long> needInsertList = CollUtil.subtract(roleIdList, dbRoleIdList);
        if (CollUtil.isNotEmpty(needInsertList)) {
            List<SysUserRoleEntity> sysUserRoleEntities = needInsertList.stream().map(roleId -> {
                SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
                sysUserRoleEntity.setUserId(userId);
                sysUserRoleEntity.setRoleId(roleId);
                return sysUserRoleEntity;
            }).collect(Collectors.toList());

            saveBatch(sysUserRoleEntities);
        }

        // 传入的没有，数据库有，删除
        Collection<Long> needRemoveList = CollUtil.subtract(dbRoleIdList, roleIdList);
        if (CollUtil.isNotEmpty(needRemoveList)) {
            remove(Wrappers.<SysUserRoleEntity>lambdaQuery().in(SysUserRoleEntity::getRoleId, needRemoveList));
        }
    }


    /**
     * 查询指定用户的角色ID列表
     *
     * @param userId 用户ID
     * @return 角色ID列表
     */
    public List<Long> getRoleIdList(Long userId) {
        return lambdaQuery().eq(SysUserRoleEntity::getRoleId, userId).list()
                .stream().map(SysUserRoleEntity::getRoleId)
                .collect(Collectors.toList());
    }


    /**
     * 删除用户列表的 用户角色关联关系
     *
     * @param userIdList 用户ID列表
     */
    public void deleteByUserIdList(List<Long> userIdList) {
        remove(Wrappers.<SysUserRoleEntity>lambdaQuery().in(SysUserRoleEntity::getUserId, userIdList));
    }

    /**
     * 通过角色ID删除 用户角色关联关系
     *
     * @param roleId 角色ID
     */
    public void deleteByRoleId(Long roleId) {
        remove(Wrappers.<SysUserRoleEntity>lambdaQuery().in(SysUserRoleEntity::getRoleId, roleId));
    }
}
